﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HotelManageSystem.Domain;
using HotelManageSystem.Domain.Entities;
using HotelManageSystem.Domain.Infrastructure;
using HotelManageSystem.Models;
using Telerik.Web.Mvc;

namespace HotelManageSystem.Controllers
{
    public class PostController : Controller
    {
        private IPostRepository postRepository;
        private IUnitOfWork unitOfWork;
        public PostController(IPostRepository postRepository, IUnitOfWork unitOfWork)
        {
            this.postRepository = postRepository;
            this.unitOfWork = unitOfWork;
        }

        private IEnumerable<PostModel> GetPostModel()
        {
            return from post in postRepository.GetAll().AsQueryable()
                   select new PostModel
                              {
                                  ID = post.ID,
                                  Title = post.Title,
                                  Remark = post.Remark
                              };
        }

        public PartialViewResult Index()
        {
            return PartialView(GetPostModel());
        }

        [GridAction]
        public ActionResult TelerikAjax()
        {
            return View(new GridModel(GetPostModel()));
        }

        [HttpPost]
        [GridAction]
        public ActionResult Insert()
        {
            Post post = new Post();

            if (TryUpdateModel(post))
            {
                postRepository.Add(post);
            }
            unitOfWork.Commit();
            return View(new GridModel(GetPostModel()));
        }

        [HttpPost]
        [GridAction]
        public ActionResult Update(int id)
        {
            Post post = postRepository.GetById(id);
            if (post != null)
            {
                if (TryUpdateModel(post))
                {
                    postRepository.Update(post);
                }
            }
            unitOfWork.Commit();
            return View(new GridModel(GetPostModel()));
        }

        [HttpPost]
        [GridAction]
        public ActionResult Delete(int id)
        {
            Post post = postRepository.GetById(id);
            if (post != null)
            {
                postRepository.Delete(post);
            }
            unitOfWork.Commit();
            return View(new GridModel(GetPostModel()));
        }
    }
}
